from __future__ import division
import sys,os,time
from src.Equipments.LockIn import SR830
from src.Equipments.RFGenerator import E8257D
from src.Equipments.multimeter import AgilentMulti
from src.Equipments.gaussmeter import Lakeshore455
from src.Equipments.EDMR_magnet import EDMRmagnet

from src.Data.DataStructure import Data

import numpy as np
import matplotlib.pyplot as plt

User="PierreAndre"
#import pylab as plb
home_path=os.getcwd()+os.sep#Current path to this program
sys.path.append(home_path+"src"+os.sep)
data_path=home_path+"Users"+os.sep+User+os.sep+"data"+os.sep#For saving later on data
#print data_path

#########################################################
### Parameters - Sweeping settings
#########################################################
#frequency_start=7033-100 #MHz
#frequency_stop=7033+100 #MHz

Field_min=-2
Field_max=10 #mT
Field_resolution=0.01 #mT

#Minimum waiting time = about 300 ms (plot time is limitant)
waiting_time=500	#ms, Waiting time for each point

number_of_points=np.abs(int((Field_max-Field_min)/Field_resolution)) #Total number of points
Field_step=np.abs(Field_max-Field_min)/number_of_points
print "Scan between %d mT and %d mT at %d mT/min: %d points" %(Field_min,Field_max,Field_step,number_of_points)

test=True #If standalone without anything connected->True
#########################################################
#########################################################


#########################################################
### Parameters - Magnet
#########################################################
magnet=EDMRmagnet(test)
#########################################################
#########################################################

#########################################################
### Parameters - Gaussmeter
#########################################################
gaussmeter=Lakeshore455("GPIB0::12::INSTR",test)
#########################################################
#########################################################

#########################################################
### Parameters - RF setup
#########################################################
if False:
	RF=E8257D("GPIB0::10::INSTR","FM",test)
	RF.Set_Modulation(5232,100)	#Frequency Hz, Modulation deviation kHz / amplitude dB
	RF.Set_Modulation_Output(False,False)	#Modulation On = True, LFOutput On = True
	RF.Set_Power(3)	#dBm
	RF.Set_Frequency(frequency_start)
	RF.Set_Output_ONOFF(True)
#########################################################
#########################################################


#########################################################
### Parameters - Data saving
#########################################################
data=Data(given_name="SiBi-650C-vac",
		path=data_path,
		comments="",
		rows=number_of_points,
		columns=4,#Field, A channel
		light=8, #V
		temperature=10,#K
		scan_mode="field",
		phase=0,#in degree
		modulation_frequency=5.141,#in kHz
		modulation_amplitude=1,#in mT
		receiver_mode=2,
		receiver_gain=1,
		time_constant=0.3, #in s
		frequency=200,#MHz
		power=0,#mW
		picture_saving_format='eps',
		user=User)
data.step=0 #Initial value
#########################################################
#########################################################

#########################################################
### Measure
#########################################################
def DoMeasure(arg):
	#Change frequency
	#frequency=frequency_start+i*(frequency_stop-frequency_start)/(number_of_points-1)
	#RF.Set_Frequency(frequency)#MHz
	#data.data[i,0]=frequency
	ti=time.time()
	if data.step <number_of_points-1:
		X,Y=lockin.Read_XY()
		data.data[data.step,1]=gaussmeter.Measure_Field()
		data.data[data.step,2]=X
		data.data[data.step,3]=Y
		print "Step",data.step,"B0 = ",data.data[data.step,0]," mT, X = ",X,"V, Y = ",Y,"V"
		#print "f = ",frequency,"MHz, A = ",data.data[i,1],"V, B = ",data.data[i,2],"V"
		data.step+=1
		#Update field
		magnet.SetMagneticField(data.data[data.step,0], "millitesla")
	elif data.step == number_of_points-1:
		X,Y=lockin.Read_XY()
		data.data[data.step,1]=gaussmeter.Measure_Field()
		data.data[data.step,2]=X
		data.data[data.step,3]=Y
		print "Step",data.step,"B0 = ",data.data[data.step,0]," mT, X = ",X,"V, Y = ",Y,"V"
		data.Save_data()
		#has to be after data.Save_data because that method fill the self.full_saving_path value
		plt.savefig(data.full_saving_path+'.'+data.picture_saving_format,format=data.picture_saving_format)
		data.step+=1
		#Update field
		magnet.SetMagneticField(data.data[data.step,0], "millitesla")
		print "Complete."
		magnet.CloseRessource()
		
	else:
		pass
	DoTime=time.time()-ti
	if waiting_time-DoTime*1000<=0:
		DeltaTDo=waiting_time
	else:
		DeltaTDo=waiting_time-DoTime*1000
	TimerDo.interval=DeltaTDo
#########################################################
#########################################################


#########################################################
### Plotting
#########################################################
fig = plt.figure(1)

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
ax1.grid(True)
ax1.set_title("Magnetic field sweep")
ax1.set_ylabel("EDMR signal (V)")
ax1.axis([0,1,0,1])
ax2.grid(True)
ax2.set_xlabel("B0 field (mT)")
ax2.set_ylabel("EDMR signal (V)")
ax2.axis([0,1,0,1])
line1=ax1.plot([0,1],[0,1],'o-k')
line2=ax2.plot([0,1],[0,1],'o-r')
manager = plt.get_current_fig_manager()

def RealtimePloter(arg):
	global values
	ti=time.time()
	if data.step>0:
		line1[0].set_data(data.data[0:data.step,0],data.data[0:data.step,2])
		ax1.axis([data.data[0:data.step,0].min(),data.data[0:data.step,0].max(),data.data[0:data.step,2].min(),data.data[0:data.step,2].max()])
		line2[0].set_data(data.data[0:data.step,0],data.data[0:data.step,3])
		ax2.axis([data.data[0:data.step,0].min(),data.data[0:data.step,0].max(),data.data[0:data.step,3].min(),data.data[0:data.step,3].max()])
		manager.canvas.draw()
	PlotTime=time.time()-ti
	if waiting_time-PlotTime*1000<=0:
		DeltaTPlot=waiting_time
	else:
		DeltaTPlot=waiting_time-PlotTime*1000
	TimerPlot.interval=DeltaTPlot
	#manager.show()

lockin.Reset_Memory()

#Start the magnet
magnet.OpenRessource()
magnet.SetMagneticField(data.data[data.step,0], "millitesla")
time.sleep(5)

TimerPlot = fig.canvas.new_timer(interval=waiting_time)
TimerPlot.add_callback(RealtimePloter, ())
TimerDo = fig.canvas.new_timer(interval=waiting_time)
TimerDo.add_callback(DoMeasure, ())
TimerPlot.start()
TimerDo.start()

plt.show()	
magnet.CloseRessource()
#########################################################
#########################################################